package org.springblade.oa.tool;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springblade.core.boot.file.BladeFileUtil;
import org.springblade.core.tool.constant.SystemConstant;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Arrays;
import java.util.List;

/**
 * @author LK
 * @version 1.0.0
 * @Title: ImageUtil.java
 * @Description: TODO    图片工具类
 * @date 2020/4/16 11:33
 */
public class ImageUtil {

	/**
	 * 是否是图片
	 *
	 * @param files
	 * @return
	 */
	public static boolean isImage(MultipartFile[] files) {
		if (null != files && files.length > 0) {
			List<MultipartFile> multipartFiles = Arrays.asList( files );
			BufferedImage image = null;
			try {
				for (MultipartFile multipartFile : multipartFiles) {
					image = ImageIO.read( multipartFile.getInputStream() );
					if (image == null || image.getWidth() <= 0 || image.getHeight() <= 0) {
						System.out.println( "请检查，包含非图片文件" );
						return false;
					}
				}
				return true;
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
		return false;
	}

	/**
	 * 删除图片
	 *
	 * @param path
	 * @return
	 */
	public static boolean delImage(String path) {
		if (StringUtils.isBlank( path )) {
			return false;
		}
		File file = new File( path );
		if (file.exists()) {
			file.delete();
			return true;
		}
		return false;
	}

	/**
	 * 下载图片
	 */
	public static void downloadImage(HttpServletResponse response, String path) {
		File file = new File( path );
		String fileName;
		if (file.exists()) {
			fileName = path.substring( path.lastIndexOf( "/" ) + 1 );
			// 设置强制下载不打开
			response.setContentType( "application/force-download" );
			response.addHeader( "Content-Disposition", "attachment;fileName=" + fileName );
			byte[] buffer = new byte[1024];
			FileInputStream fis = null;
			BufferedInputStream bis = null;
			try {
				fis = new FileInputStream( file );
				bis = new BufferedInputStream( fis );
				OutputStream outputStream = response.getOutputStream();
				int i = bis.read( buffer );
				while (i != -1) {
					outputStream.write( buffer, 0, i );
					i = bis.read( buffer );
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (bis != null) {
					try {
						bis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (fis != null) {
					try {
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	/**
	 * 图片预览
	 *
	 * @param response
	 * @param path
	 */
	public static void preView(HttpServletResponse response, String path) {
		File file = new File( path );
		String fileName;
		if (file.exists()) {
			fileName = path.substring( path.lastIndexOf( "/" ) + 1 );
			//设置响应头
			response.setHeader( "Access-Control-Allow-Origin", "*" );
			try {
				response.getOutputStream().write( FileUtils.readFileToByteArray( file ) );
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 批量下载文件
	 *
	 * @param response
	 * @param pathList
	 */
	public static void downloadBatch(HttpServletResponse response, List<String> pathList, String zipName) {
		if (null != pathList && !pathList.isEmpty()) {
			//创建临时文件夹
			String uploadRealPath = SystemConstant.me().getUploadRealPath();
			File tempDirectory = new File( uploadRealPath + "/福利费文件" );
			if (!tempDirectory.exists()) {
				tempDirectory.mkdirs();
			}
			//copy源文件到临时文件
			for (int i = 0; i < pathList.size(); i++) {
				String newFileName = "";
				String hzm = pathList.get( i ).substring( pathList.get( i ).lastIndexOf( "." ));//后缀名
				if(pathList.size()>1){
					newFileName = tempDirectory + File.separator + zipName + (i+1)+hzm ;
				}else{
					newFileName = tempDirectory + File.separator +zipName+hzm;
				}
				ImageUtil.fileCopyRightWay( pathList.get( i ), newFileName );
				/*File rouseFile = new File( s );
				try {
					FileUtils.copyFileToDirectory( rouseFile, tempDirectory );
				} catch (IOException e) {
					e.printStackTrace();
				}*/
			}
			//设置文本类型
			response.setContentType( "application/zip" );
			//设置响应头
			try {
				response.setHeader( "Content-Disposition", "attachment; filename=" + new String( zipName.getBytes( "GBK" ), "iso8859-1" )
					+ ".zip" );
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			//下载压缩文件
			try {
				ZipUtils.toZip( tempDirectory.getPath(), response.getOutputStream(), true );
			} catch (IOException e) {
				e.printStackTrace();
			}
			//删除临时文件和文件夹
			deleteFile( tempDirectory );
		}
	}

	/**
	 * 递归删除文件以及文件夹下文件
	 *
	 * @param file
	 */
	public static void deleteFile(File file) {
		if (file.exists()) {
			if (file.isDirectory()) {
				File[] files = file.listFiles();
				for (File file1 : files) {
					deleteFile( file1 );
				}
			}
			//直接删除文件
			file.delete();
		}
	}

	/**
	 * 判断文件是否为图片或者pdf文件
	 *
	 * @param files
	 * @return
	 */
	public static boolean isImageOrPdf(MultipartFile[] files) {
		if (null != files && files.length > 0) {
			List<MultipartFile> multipartFiles = Arrays.asList( files );
			BufferedImage image = null;
			try {
				for (MultipartFile multipartFile : multipartFiles) {
					String s = BladeFileUtil.getFileExt( multipartFile.getOriginalFilename() ).toUpperCase();
					if (".PDF".equals( s )) {
						System.out.println( ".PDF文件" );
						continue;
					}
					image = ImageIO.read( multipartFile.getInputStream() );
					if (image == null || image.getWidth() <= 0 || image.getHeight() <= 0) {
						System.out.println( "请检查，包含非图片、PDF文件" );
						return false;
					}
				}
				return true;
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
		return false;
	}

	/**
	 * 判断文件是否为图片或者pdf文件或者word文件
	 *
	 * @param files
	 * @return
	 */
	public static boolean isImageOrPdfOrWord(MultipartFile[] files) {
		if (null != files && files.length > 0) {
			List<MultipartFile> multipartFiles = Arrays.asList( files );
			BufferedImage image = null;
			try {
				for (MultipartFile multipartFile : multipartFiles) {
					String s = BladeFileUtil.getFileExt( multipartFile.getOriginalFilename() ).toUpperCase();
					if (".PDF".equals( s )) {
						System.out.println( ".PDF文件" );
						continue;
					} else if (".DOCX".equals( s ) || ".DOC".equals( s )) {
						System.out.println( "word文件" );
						continue;
					}
					image = ImageIO.read( multipartFile.getInputStream() );
					if (image == null || image.getWidth() <= 0 || image.getHeight() <= 0) {
						System.out.println( "请检查，包含非图片、PDF文件、word文件" );
						return false;
					}
				}
				return true;
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
		return false;
	}

	/**
	 * 用缓冲区读写，来提升读写效率。
	 */
	public static void fileCopyRightWay(String srcFile, String newFile) {
		FileInputStream in = null;
		FileOutputStream out = null;
		try {
			in = new FileInputStream(srcFile);
			out = new FileOutputStream(newFile,true);
			byte[] buf = new byte[1024];//缓冲区
			int len;
			while ((len = in.read( buf )) != -1) {
				out.write( buf, 0, len );//读几个写几个
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
